package com.iceberg.adgt.domain;

import com.iceberg.adgt.common.DomainException;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

final class Layer {

	private final Map<String, Layer> allowedLayers = new HashMap<String, Layer>();
	private final Set<Unit> units = new HashSet<Unit>();

	private String name;
	private Set<Rule> rules = new HashSet<Rule>();
	private int number;

	Layer(String name, int number) throws DomainException {
		if (!name.equals("") && number > 0) {
			this.name = name;
			this.number = number;
		} else {
			throw new DomainException("Name cannot be empty and number must be greater than 0.");
		}
	}

	void addAllowedLayer(Layer layer) throws DomainException {
		if (!getAllowedLayers().containsValue(layer)) {
			allowedLayers.put(layer.getName(), layer);
		} else {
			throw new DomainException("That layer is allready defined!");
		}
	}

	void removeAllowedLayer(String layerName) {
		allowedLayers.remove(layerName);
	}

	Map<String, Layer> getAllowedLayers() {
		return allowedLayers;
	}

	String getName() {
		return name;
	}

	int getNumber() {
		return number;
	}

	Set<Unit> getUnits() {
		return units;
	}

	boolean removeRule(Rule rule) {
		return rules.remove(rule);
	}

	void setRules(Set<Rule> rules) {
		this.rules = rules;
	}

	Set<Rule> getRules() {
		return rules;
	}

	void addUnit(Unit unit) throws DomainException {
		for (Unit u : units) {
			if (u.getName().equals(unit.getName()) && u.getType().equals(unit.getType())) {
				throw new DomainException("Unit already exists in this layer!");
			}
		}
		units.add(unit);
	}

	void removeUnitByUnitName(String unitName, String unitType) {
		for (Unit unit : units) {
			if (unit.getName().equals(unitName) && unit.getType().name().equals(unitType)) {
				units.remove(unit);
				return;
			}
		}
	}

	@Override
	public String toString() {
		return this.getName();
	}
}
